package com.wt.myaop.config;

import com.wt.myaop.anno.MyAnnotation;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.PointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor;
import org.springframework.context.annotation.Bean;

import java.lang.reflect.Method;

/**
 * @description
 * @author: wangtao
 * @date:17:23 2019/6/4
 * @email:386427665@qq.com
 */
public class MyAroundConfiguration {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Bean
    public PointcutAdvisor myAopPointCutAdvisor() {
        return new StaticMethodMatcherPointcutAdvisor(new MyAopAroundPointCutAdvice()) {
            @Override
            public boolean matches(Method method, Class<?> aClass) {
                // 匹配方法上标有特定注解的方法进行aop拦截
                return method.getAnnotation(MyAnnotation.class) != null;
            }
        };
    }

    public class MyAopAroundPointCutAdvice implements MethodInterceptor {

        @Override
        public Object invoke(MethodInvocation mi) throws Throwable {
            log.info("------------------my args monitor start--------------------");
            Object[] args = mi.getArguments();
            for (int i = 0; i < args.length; i++) {
                log.info("args[{}]={}", i, args[i]);
            }
            Object ret = mi.proceed();
            log.info("------------------my args monitor end--------------------");
            return ret;
        }
    }

}
